package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // log.info("TokenInterceptor进入到资源方法之前");

        if (true) {
            CurrentHolder.setUserId(2);
            return true;
        }

        System.out.println("TokenInterceptor使用的线程名称是：" + Thread.currentThread().getName());
        //
        // 从请求头中获取token
        String token = request.getHeader("token");
        try {
            // 解析token
            Claims claims = JwtUtils.parseJWT(token);

            Integer userId = claims.get("userId", Integer.class);
            CurrentHolder.setUserId(userId);
        } catch (Exception e) {
            // 解析错误   响应401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        // return false;  // 直接拦截  不能再进入资源方法
        return true;    //放行    进入资源方法
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        // log.info("TokenInterceptor从资源方法出来之后");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // log.info("TokenInterceptor完成页面渲染");
        CurrentHolder.removeUserId();

    }
}